﻿//===============================================================================
// Magic OQL
//===============================================================================
// Copyright ?Magic Thought Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// Richie (http://www.cnblogs.com/RicCC)
// March 10, 2008
//===============================================================================

using Antlr.Runtime;
using Antlr.Runtime.Tree;

namespace SQLAnalyticLibrary.Expressions.Function
{
    /// <summary>
    /// Select clause
    /// </summary>
    public class UserFunction : Expression
    {
        private int _count = 0;
        #region constructors
        public UserFunction(Expression node)
            : base(node.Token)
        {
            this.Token.Text = string.Empty;
        }
        public UserFunction(IToken t)
            : base(t)
        {
            this.Token.Text = string.Empty;
        }
        #endregion

        public override void AddChild(Expression t)
        {
            if (t == null)
            {
                this.InternalAddChild(t);
                return;
            }
            if (this._count == 0) //the first child should be the function name.
            {
                if (!t.IsNil) //pick up function name
                    this.Token.Text = t.Text; 
                else if (t._children != null && t._children.Count > 0)
                {
                    //pick up function name
                    this.Token.Text = t._children[0].Text;
                    t._children.RemoveAt(0);
                    this.InternalAddChild(t);
                }
            }
            else this.InternalAddChild(t);
            if (!t.IsNil || t._children != null)
                this._count++;
        }
        public override Expression DupNode()
        {
            return new UserFunction(this);
        }
        public override void VisitSql(ISqlVisitor visitor)
        {
            visitor.Sql(this.ToString()); //function name
            visitor.Sql("(");
            this.InternalVisitSql(visitor, true, ","); //other elements of function
            visitor.Sql(")");
        }
    }
}
